//
//  ViewController.m
//  NSPredicate的使用
//
//  Created by 梁森 on 2018/7/21.
//  Copyright © 2018年 梁森. All rights reserved.
//

#import "ViewController.h"

#import "Person.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor yellowColor];
    
    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"age > 25"];
    
    Person * p1 = [[Person alloc] init];
    p1.name = @"1";
    p1.age = 31;
    
    // 单个对象
    NSLog(@"%d", [predicate evaluateWithObject:p1]);
    
    NSMutableArray * personArr = [NSMutableArray array];
    for (NSInteger i = 0; i < 10; i ++) {
        Person * p = [[Person alloc] init];
        p.name = [NSString stringWithFormat:@"人物：%lu", i];
        p.age = i +20;
        [personArr addObject:p];
    }
    // 过滤数组
    NSArray * results = [personArr filteredArrayUsingPredicate:predicate];  // 数组中人物年龄大于25的元素
    NSLog(@"%@", results);
    NSLog(@"%@", [results valueForKey:@"age"]);
    NSPredicate * namePredicate = [NSPredicate predicateWithFormat:@"name CONTAINS '人物'"];  // 数组中人物名字包含人物的元素
    NSLog(@"%@", [personArr filteredArrayUsingPredicate:namePredicate]);
    
    // 模糊搜索
    NSArray * names = @[@"Zhao", @"Qian", @"Sun", @"Li"];
    NSPredicate * containPredicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS 'n'"];    // 过滤所有包含n的名字
    NSLog(@"%@", [names filteredArrayUsingPredicate:containPredicate]);
    
    // 求两个数组的交集
    NSArray * arr1 = @[@(1), @(2), @(3), @(4)];
    NSArray * arr2 = @[@(3), @(4), @(5), @(6)];
    NSPredicate * arrPredicate = [NSPredicate predicateWithFormat:@"SELF in %@", arr2];
    NSLog(@"%@", [arr1 filteredArrayUsingPredicate:arrPredicate]);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
